import {
  HttpStatus,
  HttpException,
  Controller,
  Get,
  Post,
  Body,
  Param,
  Delete,
  Logger,
  UploadedFile,
  UseInterceptors,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { PlatformService } from './platform.services';
import { PrismaService } from 'src/database/prisma.service';
import { ApiTags } from '@nestjs/swagger';
import { CreatePlatformDto } from './dto/create-platform.dto';

@ApiTags('platform')
@Controller('platform')
export class PlatformController {
  constructor(
    private readonly appService: PlatformService,
    private readonly prismaService: PrismaService,
  ) {}
  @Get('/list')
  async platformlist(): Promise<string | undefined> {
    const value = await this.appService.getAllPlatforms();
    if (value) {
      return JSON.stringify(value);
    }
    new HttpException(`None platforms defined`, HttpStatus.NOT_FOUND);
  }

  @Get('/:id')
  async platform(@Param('id') id: string): Promise<string | undefined> {
    const iid = Number(id);
    if (isNaN(iid)) {
      throw new HttpException('No platforms found', HttpStatus.NOT_FOUND);
    }
    const value = await this.appService.getPlatform(iid);
    if (value) {
      Logger.log(`find platform ${value.name}`);
      return JSON.stringify(value);
    }
    new HttpException(`Can not find platform ${id}`, HttpStatus.NOT_FOUND);
  }
  @Delete('/:id')
  async deletePlatform(@Param('id') id: string) {
    const platformId = parseInt(id, 10);
    return this.appService.delete(platformId);
  }
  @Post()
  async create(@Body() platform: CreatePlatformDto): Promise<string> {
    const value = await this.appService.create(platform);
    if (value) {
      return JSON.stringify(value);
    } else {
      throw new HttpException(
        `Create platform ${platform.name} failed`,
        HttpStatus.BAD_REQUEST,
      );
    }
  }
  @Post('withcookie')
  @UseInterceptors(FileInterceptor('file'))
  async createWithCookie(
    @UploadedFile() file: Express.Multer.File,
    @Body('name') name: string,
    @Body('url') url: string,
    @Body('cookieName') cookieName: string,
  ): Promise<string> {
    Logger.log(
      `received create platformwithcookie ${name} ${url} ${cookieName} ${file.originalname}`,
    );
    const platform = {
      name: name,
      url: url,
    };
    const platformDB = await this.appService.create(platform);
    if (!platformDB) {
      throw new HttpException(
        `Create platform ${platform.name} failed`,
        HttpStatus.BAD_REQUEST,
      );
    }
    const cookie = await this.prismaService.cookie.create({
      data: {
        name: cookieName,
        filename: file.originalname,
        content: file.buffer.toString('utf-8'), // Buffer directly from file
        platformId: platformDB.id,
      },
    });
    if (cookie) {
      return JSON.stringify({ message: 'successful', data: platformDB });
    }
    throw new HttpException(
      `Create platform cookie ${platform.name} failed`,
      HttpStatus.BAD_REQUEST,
    );
  }

  @Post('list')
  async platforms(@Body() platforms: string[]): Promise<string> {
    const ids = platforms.map((i) => Number(i));
    const values = await this.appService.getPlatforms(ids);
    if (values) {
      return JSON.stringify(values);
    } else {
      throw new HttpException(`Find platforms failed`, HttpStatus.BAD_REQUEST);
    }
  }
}
